<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\trait\SettingsTrait;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageWinnerlookPrivacy;
use plugin\ycMassage\utils\enum\WinnerlookChannels;
use plugin\ycMassage\utils\enum\WinnerlookState;
use plugin\ycMassage\utils\Yunxin;
use support\Request;
use think\facade\Db;

class WinnerlookController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->checkboxConfig();
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('tel', 'input', '号码');
        $builder->addScreen('bind_number', 'input', '绑定号码');
        $builder->addScreen('state', 'select', '状态', [
            'options' => WinnerlookState::getOptions()
        ]);
        $builder->addTopButton('create', '添加号码', [
            'api'    => $this->pluginPrefix . '/admin/Winnerlook/create',
            'path'   => '/Winnerlook/create',
            'type'      => 'modal'
        ], [
            'customStyle' => [
                'width' => '1140px',
                'minHeight' => '800px'
            ]
        ], [
            'type' => 'success'
        ]);
        $builder->addBottomButton('deleteAll', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Winnerlook/deleteAll',
            'type'      => 'confirm',
            'method' => 'delete',
        ], [
            'type' => 'danger',
            'title'   => '温馨提示',
            'content' => '是否确认删除所选数据',
        ], [
            'type' => 'danger',
        ]);
        $builder->addBottomButton('unbindAll', '批量解绑', [
            'api'    => $this->pluginPrefix . '/admin/Winnerlook/unbindAll',
            'type'      => 'confirm',
            'method' => 'delete',
        ], [
            'type' => 'danger',
            'title'   => '温馨提示',
            'content' => '是否确认删除所选数据',
        ], [
            'type' => 'danger',
        ]);
        $builder->addRightButton('update', '编辑', [
            'api'    => $this->pluginPrefix . '/admin/Winnerlook/update',
            'path'   => '/Winnerlook/update',
            'type'      => 'modal',
            'params' => [
                'field' => 'state',
                'where' => 'in',
                'value' => [WinnerlookState::YES['value'], WinnerlookState::NO['value']]
            ],
        ], [
            'customStyle' => [
                'width' => '1140px',
                'minHeight' => '800px'
            ]
        ], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('unbind', '解绑', [
            'api'    => $this->pluginPrefix . '/admin/Winnerlook/unbind',
            'type'      => 'confirm',
            'method' => 'post',
            'params' => [
                'field' => 'state',
                'where' => '=',
                'value' => WinnerlookState::BINDING['value']
            ],
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认解绑该数据',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('delete', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Winnerlook/delete',
            'type'      => 'confirm',
            'method' => 'delete',
            'params' => [
                'field' => 'state',
                'where' => '=',
                'value' => WinnerlookState::NO['value']
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ])
            ->addColumn('tel', '号码', [
                'minWidth' => 200,
            ])
            ->addColumn('alias_id', '预约ID', [
                'width' => 160,
            ])
            ->addColumn('regions', '归属地', [
                'width' => 160,
            ])
            ->addColumn('bind_number_a', '绑定号码A', [
                'width' => 200,
            ])
            ->addColumn('bind_number_b', '绑定号码B', [
                'width' => 200,
            ])
            ->addColumnEle('channels', '号码属性', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => WinnerlookChannels::dictOptions(),
                ],
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => WinnerlookState::dictOptions(),
                    'style' => WinnerlookState::dictOptions('style'),
                ],
            ])
            ->addColumn('unbind_time', '解绑时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['saas_appid', '=', $request->saas_appid]
        ];
        $bind_number = $request->get('bind_number');
        if ($bind_number) {
            $where[] = ['bind_number_a|bind_number_b', 'like', "%{$bind_number}%"];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['state', '=', $state];
        }
        $tel = $request->get('tel');
        if ($tel) {
            $where[] = ['tel', 'like', "%{$tel}%"];
        }
        $data = MassageWinnerlookPrivacy::where($where)->order('id desc')->paginate([
            'list_rows' => $limit,
            'page' => $page,
        ])->each(function ($item) {
            $item->regions = $item->province;
            if ($item->city) {
                $item->regions .= ' ' . $item->city;
            }
        });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {

        $saas_appid = $request->saas_appid;
        if ($request->method() === 'POST') {
            $D = $request->post();
            if (empty($D['tel'])) {
                return $this->fail('号码不能为空');
            }
            if (empty($D['channels'])) {
                return $this->fail('号码属性不能为空');
            }
            Db::startTrans();
            try {
                $MassageWinnerlookPrivacy = new MassageWinnerlookPrivacy;
                $MassageWinnerlookPrivacy->saas_appid = $saas_appid;
                $MassageWinnerlookPrivacy->tel = $D['tel'];
                $MassageWinnerlookPrivacy->channels = $D['channels'];
                $MassageWinnerlookPrivacy->state = $D['state'];
                if (!empty($D['regions'])) {
                    $province_id = $D['regions'][0];
                    $MassageWinnerlookPrivacy->province_id = (int)$province_id;
                    $MassageWinnerlookPrivacy->province = MassageRegions::where(['id' => $province_id])->value('title');
                    if (!empty($D['regions'][1])) {
                        $city_id = $D['regions'][1];
                        $MassageWinnerlookPrivacy->city_id = $city_id;
                        $MassageWinnerlookPrivacy->city = MassageRegions::where(['id' => $city_id])->value('title');
                    }
                }
                $MassageWinnerlookPrivacy->save();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            return $this->success('添加成功');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($request, $builder);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $saas_appid = $request->saas_appid;
        $MassageWinnerlookPrivacy = MassageWinnerlookPrivacy::where(['id' => $id, 'saas_appid' => $saas_appid])->whereIn('state', [WinnerlookState::YES['value'], WinnerlookState::NO['value']])->find();
        if (!$MassageWinnerlookPrivacy) {
            return $this->fail('数据不存在或状态不可编辑');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            if (empty($D['tel'])) {
                return $this->fail('号码不能为空');
            }
            if (empty($D['channels'])) {
                return $this->fail('号码属性不能为空');
            }
            Db::startTrans();
            try {
                $MassageWinnerlookPrivacy->tel = $D['tel'];
                $MassageWinnerlookPrivacy->channels = $D['channels'];
                $MassageWinnerlookPrivacy->state = $D['state'];
                if (!empty($D['regions'])) {
                    $province_id = $D['regions'][0];
                    $MassageWinnerlookPrivacy->province_id = (int)$province_id;
                    $MassageWinnerlookPrivacy->province = MassageRegions::where(['id' => $province_id])->value('title');
                    if (!empty($D['regions'][1])) {
                        $city_id = $D['regions'][1];
                        $MassageWinnerlookPrivacy->city_id = $city_id;
                        $MassageWinnerlookPrivacy->city = MassageRegions::where(['id' => $city_id])->value('title');
                    }
                }
                $MassageWinnerlookPrivacy->save();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            return $this->success('编辑成功');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $data = $MassageWinnerlookPrivacy->toArray();
        $data['regions'] = [];
        if ($MassageWinnerlookPrivacy->province_id) {
            $data['regions'][] = (int)$MassageWinnerlookPrivacy->province_id;
        }
        if ($MassageWinnerlookPrivacy->city_id) {
            $data['regions'][] = (int)$MassageWinnerlookPrivacy->city_id;
        }
        $this->getFormBuilder($request, $builder);
        $data = $builder->setFormData($data)->create();
        return $this->successRes($data);
    }
    public function getFormBuilder(Request $request, $builder)
    {
        $builder->addRow('tel', 'input', '号码', '', [
            'col' => 12,
            'props' => [
                'type' => 'tel',
                'placeholder' => '请输入号码'
            ]
        ]);
        $regions = MassageRegions::getCache($request->saas_appid);
        $regionsData = [];
        foreach ($regions as $key => $province) {
            $temp = [
                'id' => $province['id'],
                'title' => $province['title'],
                'children' => []
            ];
            foreach ($province['children'] as $key => $city) {
                $temp['children'][] = [
                    'id' => $city['id'],
                    'title' => $city['title'],
                    'children' => []
                ];
            }
            $regionsData[] = $temp;
        }
        $builder->addRow('regions', 'city', '归属地', [], [
            'col' => 12,
            'options' => $regionsData,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'checkStrictly' => true,
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ],
            'prompt' => [
                'text' => "选择归属地之后，只有在该地区的用户才能能使用该号码",
            ],
        ]);
        $builder->addRow('channels', 'select', '号码属性', '', [
            'col' => 12,
            'options' => WinnerlookChannels::getOptions()
        ]);
        $builder->addRow('state', 'radio', '状态', WinnerlookState::YES['value'], [
            'col' => 12,
            'options' => WinnerlookState::getOptions()
        ]);
    }
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $saas_appid = $request->saas_appid;
        $MassageWinnerlookPrivacy = MassageWinnerlookPrivacy::where(['id' => $id, 'saas_appid' => $saas_appid, 'state' => WinnerlookState::NO['value']])->find();
        if (!$MassageWinnerlookPrivacy) {
            return $this->fail('数据不存在或状态不可删除');
        }
        $MassageWinnerlookPrivacy->delete();
        return $this->success('删除成功');
    }
    public function deleteAll(Request $request)
    {
        $ids = $request->post('id');
        Db::startTrans();
        try {
            $MassageOrders = MassageWinnerlookPrivacy::where(['saas_appid' => $request->saas_appid, 'state' => WinnerlookState::NO['value']])->whereIn('id', $ids)->select();
            foreach ($MassageOrders as $item) {
                $item->delete();
            }
            Db::commit();
            return $this->success('删除成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function unbind(Request $request)
    {
        $id = $request->post('id');
        $saas_appid = $request->saas_appid;
        $MassageWinnerlookPrivacy = MassageWinnerlookPrivacy::where(['id' => $id, 'saas_appid' => $saas_appid, 'state' => WinnerlookState::BINDING['value']])->find();
        if (!$MassageWinnerlookPrivacy) {
            return $this->fail('数据不存在或状态不可解绑');
        }
        try {
            $Yunxin = new Yunxin($saas_appid);
            $data = [
                'middleNumber' => $MassageWinnerlookPrivacy->tel,
                'bindNumberA' => $MassageWinnerlookPrivacy->bind_number_a,
                'bindNumberB' => $MassageWinnerlookPrivacy->bind_number_b,
                'mode' => '0'
            ];
            $Yunxin->middleNumberUnbind($data);
        } catch (\Throwable $th) {
        }
        $MassageWinnerlookPrivacy->state = WinnerlookState::YES['value'];
        $MassageWinnerlookPrivacy->alias_id = null;
        $MassageWinnerlookPrivacy->bind_number_a = null;
        $MassageWinnerlookPrivacy->bind_number_b = null;
        $MassageWinnerlookPrivacy->unbind_time = null;
        $MassageWinnerlookPrivacy->save();

        return $this->success('解绑成功');
    }
    public function unbindAll(Request $request)
    {
        $ids = $request->post('id');
        $MassageOrders = MassageWinnerlookPrivacy::where(['saas_appid' => $request->saas_appid, 'state' => WinnerlookState::BINDING['value']])->whereIn('id', $ids)->select();
        foreach ($MassageOrders as $item) {
            try {
                $Yunxin = new Yunxin($request->saas_appid);
                $data = [
                    'middleNumber' => $item->tel,
                    'bindNumberA' => $item->bind_number_a,
                    'bindNumberB' => $item->bind_number_b,
                    'mode' => '0'
                ];
                $Yunxin->middleNumberUnbind($data);
            } catch (\Throwable $th) {
            }
            $item->state = WinnerlookState::YES['value'];
            $item->alias_id = null;
            $item->bind_number_a = null;
            $item->bind_number_b = null;
            $item->unbind_time = null;
            $item->save();
        }
        return $this->success('解绑成功');
    }
}
